package com.sgcc.lms.openstack.service.impl;

import com.fasterxml.jackson.databind.ObjectMapper;
import com.sgcc.lms.openstack.exception.*;
import com.sgcc.lms.openstack.service.GlanceService;
import com.sgcc.lms.openstack.util.OpenStackClientFactory;
import com.sgcc.lms.openstack.util.RestClientUtil;
import lombok.extern.slf4j.Slf4j;
import org.apache.http.client.methods.HttpPatch;
import org.apache.http.entity.StringEntity;
import org.openstack4j.api.OSClient;
import org.openstack4j.model.common.ActionResponse;
import org.openstack4j.model.common.Payload;
import org.openstack4j.model.common.Payloads;
import org.openstack4j.model.image.v2.Image;
import org.openstack4j.openstack.image.v2.domain.GlanceImage;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.util.HashMap;
import java.util.List;

/**
 * @Author: 李孟帅
 * @CreateTime: 2020-07-21 14:19
 * @Description:
 */
@Service
@Slf4j
public class GlanceServiceImpl implements GlanceService {
    @Value("${glance.endpoint}")
    private String endpoint;
    private static final String LINE = "==========================================》{}";

    /**
     * @Author 李孟帅
     * @Description 列出镜像
     * @Date 2020/7/21
     **/
    @Override
    public List<? extends Image> images(String tokenId) throws NullTokenException {
        //获取os客户端
        OSClient.OSClientV3 osClient = OpenStackClientFactory.getOpenStackClient(tokenId);
        HashMap<String, String> map = new HashMap<>(4);
        //排序条件
        map.put("sort", "name:desc,status:desc");
        //列出镜像
        List<? extends Image> list = osClient.imagesV2().list();
        return list;
    }

    /**
     * @Author 李孟帅
     * @Description 获取镜像信息
     * @Date 2020/7/21
     **/
    @Override
    public Image getImage(String tokenId, String id) throws NullTokenException {
        //获取客户端
        OSClient.OSClientV3 osClient = OpenStackClientFactory.getOpenStackClient(tokenId);
        //获取镜像信息
        Image image = osClient.imagesV2().get(id);
        return image;
    }

    /**
     * @Author 李孟帅
     * @Description 创建镜像
     * @Date 2020/7/21
     **/
    @Override
    public Image createImage(String tokenId, Image image) throws NullTokenException {
        //获取客户端
        OSClient.OSClientV3 osClient = OpenStackClientFactory.getOpenStackClient(tokenId);
        //创建镜像
        Image image1 = osClient.imagesV2().create(image);
        return image1;
    }

    /**
     * @Author 李孟帅
     * @Description 更新镜像 （目前只能改名）
     * @Date 2020/7/21
     **/
    @Override
    public Image updateImage(String tokenId, Image image) throws IOException, HttpException {
        //镜像id
        String id = image.getId();
        //镜像名字
        String name = image.getName();
        //请求体
        String req = "[{\"op\":\"replace\",\"path\":\"/name\",\"value\":\"" + name + "\"}]";
        StringEntity entity = new StringEntity(req, "UTF-8");
        //构建post请求
        HttpPatch httpPatch = new HttpPatch("http://192.100.5.222:9292/v2" + "/images/" + id);
        //设置请求头
        httpPatch.setHeader("X-Auth-Token", tokenId);
        httpPatch.setHeader("Content-Type", "application/openstack-images-v2.1-json-patch");
        //设置请求体
        httpPatch.setEntity(entity);
        //发送http请求
        String result = RestClientUtil.execute(httpPatch);
        //jackson解析
        ObjectMapper objectMapper = new ObjectMapper();
        GlanceImage glanceImage = objectMapper.readValue(result, GlanceImage.class);
        return glanceImage;
    }

    /**
     * @Author 李孟帅
     * @Description 删除镜像
     * @Date 2020/7/21
     **/
    @Override
    public ActionResponse delete(String tokenId, String id) throws NullTokenException {
        //获取客户端
        OSClient.OSClientV3 osClient = OpenStackClientFactory.getOpenStackClient(tokenId);
        //删除
        ActionResponse delete = osClient.imagesV2().delete(id);
        return delete;
    }

    /**
    * @Author 李孟帅
    * @Description 上传镜像
    * @Date 2020/7/22 
    **/
    @Override
    public ActionResponse uploadImage(String tokenId, MultipartFile file, String id) throws NullTokenException, IOException {
        //获取客户端
        OSClient.OSClientV3 openStackClient = OpenStackClientFactory.getOpenStackClient(tokenId);
        //文件名
        String originalFilename = file.getOriginalFilename();
        log.info("/images/upload,文件名" + LINE, originalFilename);
        //获取文件的输入流
        InputStream inputStream = file.getInputStream();
        //创建数据负载
        Payload<InputStream> filePayload = Payloads.create(inputStream);
        //获取镜像
        Image image = openStackClient.imagesV2().get(id);
        //上传镜像数据
        ActionResponse upload = openStackClient.imagesV2().upload(id, filePayload, image);
        return upload;
    }

    /**
    * @Author 李孟帅
    * @Description 下载镜像
    * @Date 2020/7/22 
    **/
    @Override
    public ActionResponse downloadImage(String tokenId, HttpServletResponse response,String id) throws NullTokenException {
//        OSClient.OSClientV3 openStackClient = OpenStackClientFactory.getOpenStackClient(tokenId);
//        File file = new File("C:\\tmp\\test.iso");
//        ActionResponse download = openStackClient.imagesV2().download(id, file);
//        log.info("/images/download,下载镜像" + LINE, "成功");
        return null;
    }
}
